#!/usr/bin/perl -w 
# Check status of the EC2 instance(s)
# 07/2008, Vlastimil Holer <vlastimil.holer@gmail.com>, GNU/GPL2
use Net::Amazon::EC2;
use Getopt::Std;

my %opts=(); getopts('a:s:',\%opts);
my $key_access=$opts{'a'} or die('Access key required: -a');
my $key_secret=$opts{'s'} or die('Secret key required: -s');
die('No instance IDs to check')
	unless scalar(@ARGV);

my %insts;
for my $inst (@ARGV) {
	$insts{$inst}='not found';
}

my $ec2=Net::Amazon::EC2->new(
	AWSAccessKeyId  => $key_access,
	SecretAccessKey => $key_secret,
) or die('Could not inicialize Net::Amazon::EC2');

my $desc_insts=$ec2->describe_instances();
die('Could not fetch running instances')
	unless ref $desc_insts eq 'ARRAY';

for my $ec2_res (@$desc_insts) {
	for my $ec2_inst (@{$ec2_res->{instances_set}}) {
		$insts{$ec2_inst->{instance_id}} = $ec2_inst->{instance_state}->{name}
			if exists $insts{$ec2_inst->{instance_id}};
	}
}

my $msg_brief ='';
my $msg_detail='';
for my $inst (keys %insts) {
	next if $insts{$inst} eq 'running';
	$msg_brief .=$inst.' ';
	$msg_detail.=sprintf("%-10s: %s\n",$inst,$insts{$inst});
}

if ($msg_brief) {
	print($msg_brief,"\n");
	print($msg_detail);
	exit(1);
} else {
	exit(0);
}
